<template>
  <div class="district-container">
    <a-button type="primary" class="add-district-manager" @click="handleAddService">添加客服</a-button>
    <a-table :columns="columns" :data-source="serviceData" :loading="isLoading" bordered>
      <template
        v-for="col in ['serviceName', 'serviceUsername']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e.target.value, record.key, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template slot="update" slot-scope="text, record, index">
        <div class="editable-row-operations">
        <span v-if="record.editable">
          <a-button @click="() => save(record.key)" type="primary">确认修改</a-button>
          <!--<a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
            <a>取消</a>
          </a-popconfirm>-->
        </span>
          <span v-else>
          <a-button :disabled="editingKey !== ''" @click="() => edit(record.key)" type="primary">修改</a-button>
        </span>
        </div>
      </template>
      <template slot="deleteService" slot-scope="text, record, index">
        <div class="editable-row-operations">
          <a-button @click="() => handleDelete(record.id)" type="danger">删除</a-button>
        </div>
      </template>
    </a-table>
    <a-modal v-model="addMasterVisible" title="添加客服" okText="确定" cancelText="取消"
             @ok="handleAddServiceOk" @cancel="handleAddServiceCancel">
      <div class="add-model-container">
        <a-form :form="form">
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="客服姓名"
          >
            <a-input
              v-decorator="[
          'name',
          { initialValue: '',
            rules: [{ required: true, message: '请输入合法的姓名', pattern: /^[\u4e00-\u9fa5]+$/i }] },
        ]"
              placeholder="请输入客服姓名"
            />
          </a-form-item>
          <a-form-item
            :label-col="formItemLayout.labelCol"
            :wrapper-col="formItemLayout.wrapperCol"
            label="客服电话"
          >
            <a-input
              v-decorator="[
          'username',
          { rules: [{ required: true, message: '请输入有效的电话号码', pattern: /^1[3|4|5|7|8][0-9]\d{8}$/ }] },
        ]"
              placeholder="请输入客服电话"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script>
  const columns = [
    {
      title: '序号',
      dataIndex: 'sequence',
      key: 'sequence',
      width: '5%',
      scopedSlots: { customRender: 'sequence' },
    },
    {
      title: '客服姓名',
      dataIndex: 'serviceName',
      width: '10%',
      key: 'serviceName',
      scopedSlots: { customRender: 'serviceName' },
    },
    {
      title: '客服电话',
      dataIndex: 'serviceUsername',
      key: 'serviceUsername',
      width: '10%',
      scopedSlots: { customRender: 'serviceUsername' },
    },
    {
      title: '编辑',
      dataIndex: 'update',
      key: 'update',
      width: '10%',
      scopedSlots: { customRender: 'update' },
    },
    {
      title: '删除',
      dataIndex: 'deleteService',
      key: 'deleteService',
      width: '10%',
      scopedSlots: { customRender: 'deleteService' },
    }
  ];
  const formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  const buttonFormItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
  };
  import api from '@/server/userConfig';
  export default {
    name: 'MasterService',
    components: {
    },
    props: {
      userName: String
    },
    data () {
      return {
        serviceData: [],
        columns,
        editingKey: '',
        isLoading: false,
        addMasterVisible: false,
        cacheData: [],
        formItemLayout,
        buttonFormItemLayout,
        form: this.$form.createForm(this, { name: 'dynamic_rule' }),
      }
    },
    mounted () {
      this.getMasterList();
    },
    methods: {
      // 点击删除;
      handleDelete (id) {
        this.$Modal.confirm({
          title: '确认删除此客服吗?',
          content: '',
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk: async () => {
            const res = await api.deleteService({managerServiceId: id});
            if (res.MsgCode === 0) {
              this.$message.success('删除成功');
              // 前端删除此行;
              const dataSource = [...this.serviceData];
              this.serviceData = dataSource.filter(item => item.id !== id);
            }
          },
          onCancel() {}
        })
      },
      // 点击添加客服;
      handleAddService () {
        this.addMasterVisible = true;
      },
      // 点击添加片区主管的取消;
      handleAddServiceCancel () {
        this.form.resetFields();
      },
      // 点击添加片区主管的确定;
      handleAddServiceOk () {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.addMasterVisible = false;
            // 发送ajax请求;
            this.handleAddServicePerson(this.userName, values);
            this.form.resetFields();
          }
        });
      },
      handleAddServicePerson (userName, values) {
        let serviceInformation = [];
        serviceInformation.push({serviceName: values.name, serviceUsername: values.username});
        let addAgentService = {};
        addAgentService.managerUsername = userName;
        addAgentService.serviceEntities = serviceInformation;
        const jsonData = JSON.stringify(addAgentService);
        api.addService(jsonData).then((res) => {
          if (res.MsgCode === 0) {
            this.$message.success('添加客服成功');
            this.getMasterList();
          } else {
            this.$message.info('添加失败，请核对后再重试。。。');
          }
        });
      },
      // 获取客服人员列表;
      async getMasterList() {
        this.isLoading = true;
        const res =  await api.getMasterList({username: this.userName});
        this.isLoading = false;
        if (res.MsgCode !== 0) {
          return;
        }
        let serviceData = res.Data;
        const serviceDataLength = serviceData.length;
        for (let i = 0; i < serviceDataLength; i++) {
          serviceData[i].sequence = i + 1;
          serviceData[i].key = serviceData[i].id;
          //去掉自己号码，不能操作自己的号
          if (serviceData[i].serviceUsername === this.userName) {
            serviceData.splice(i, 1);
          }
        }
        this.serviceData = serviceData;
        this.cacheData = this.serviceData.map(item => ({ ...item }));
      },

      handleChange (value, key, column) {
        const newData = [...this.serviceData];
        const target = newData.filter(item => key === item.key)[0];
        if (target) {
          target[column] = value;
          this.serviceData = newData;
        }
      },

      // 点击修改按钮;
      edit (key) {
        const newData = [...this.serviceData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = key;
        if (target) {
          target.editable = true;
          this.serviceData = newData;
        }
      },

      // 点击确认修改;
      async save (key) {
        const newData = [...this.serviceData];
        const newCacheData = [...this.cacheData];
        const target = newData.filter(item => key === item.key)[0];
        if(!/^[\u4e00-\u9fa5]+$/i.test(target.serviceName)){
          this.$message.error("请输入合法的姓名");
          return;
        } else if(!(/^1[3456789]\d{9}$/.test(target.serviceUsername))){
          this.$message.error("请输入正确的手机号");
          return;
        }
        const res = await api.updateService({
          name: target.serviceName,
          username: target.serviceUsername,
          managerServiceId: target.id,
        });
        if (res.MsgCode === 0) {
          this.$message.success('修改成功');
        }
        const targetCache = newCacheData.filter(item => key === item.key)[0];
        if (target && targetCache) {
          delete target.editable;
          this.serviceData = newData;
          Object.assign(targetCache, target);
          this.cacheData = newCacheData;
        }
        this.editingKey = '';
      },
      cancel(key) {
        const newData = [...this.serviceData];
        const target = newData.filter(item => key === item.key)[0];
        this.editingKey = '';
        if (target) {
          Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
          delete target.editable;
          this.serviceData = newData;
        }
      },
    }
  }
</script>

<style scoped>
  @import "./style.css";
</style>
